package cn.tannn.captcha.sdk.util;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class CaptchaSpringContextUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        CaptchaSpringContextUtils.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return applicationContext.getBean(name, clazz);
    }

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }


    /**
     * 该方法保证返回一个存在的 Bean，如果 Bean 不存在则抛出异常。
     * @param clazz Bean 类型
     * @param <T> 类型
     * @return 返回 Bean 实例
     * @throws NoSuchBeanDefinitionException 如果没有找到 Bean
     */
    public static <T> T getRequiredBean(Class<T> clazz) {
        T bean = applicationContext.getBean(clazz);
        if (bean == null) {
            throw new NoSuchBeanDefinitionException(clazz, "No such bean found for type: " + clazz.getName());
        }
        return bean;
    }

    /**
     * 该方法保证返回一个存在的 Bean，如果 Bean 不存在则抛出异常。
     * @param name Bean 名称
     * @param clazz Bean 类型
     * @param <T> 类型
     * @return 返回 Bean 实例
     * @throws NoSuchBeanDefinitionException 如果没有找到 Bean
     */
    public static <T> T getRequiredBean(String name, Class<T> clazz) {
        T bean = applicationContext.getBean(name, clazz);
        if (bean == null) {
            throw new NoSuchBeanDefinitionException(name, "No such bean found for name: " + name);
        }
        return bean;
    }
}
